package com.cgx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cgx.common.R;
import com.cgx.pojo.User;
import com.cgx.service.UserService;
import com.cgx.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //随机生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}", code);
            //将生成的验证码保存到Session中
            session.setAttribute(phone, code);
            return R.success("发送成功");
        }
        return R.error("发送失败");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map user, HttpSession session) {
        //获取手机号
        String phone = user.get("phone").toString();
        //获取验证码
        String code = user.get("code").toString();
        //从session中获取保存的验证码
        Object codeSession = session.getAttribute(phone);
        //验证码比对
        if (codeSession != null && codeSession.equals(code)) {
            //判断是否是新用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User userServiceOne = userService.getOne(queryWrapper);
            if (userServiceOne == null) {
                userServiceOne = new User();
                userServiceOne.setPhone(phone);
                userServiceOne.setStatus(1);
                userService.save(userServiceOne);
            }
            session.setAttribute("user", userServiceOne.getId());
            return R.success(userServiceOne);
        }
        return R.error("登录失败");
    }

}
